package com.example.personalizededucationsystem.controller;

import com.example.personalizededucationsystem.dto.request.SubmitAnswerRequest;
import com.example.personalizededucationsystem.dto.response.AnswerFeedbackResponse;
import com.example.personalizededucationsystem.dto.response.QuestionResponse;
import com.example.personalizededucationsystem.model.User;
import com.example.personalizededucationsystem.service.PracticeService;
import com.example.personalizededucationsystem.service.QuestionBankService;
import com.example.personalizededucationsystem.utils.IP_VALUE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin(origins = IP_VALUE.IP)
@RestController
@RequestMapping("/api/practice")
public class PracticeController {

    private final QuestionBankService questionBankService;
    private final PracticeService practiceService;

    @Autowired
    public PracticeController(QuestionBankService questionBankService, PracticeService practiceService) {
        this.questionBankService = questionBankService;
        this.practiceService = practiceService;
    }

    @GetMapping("/questions")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<List<QuestionResponse>> getPracticeQuestions(@RequestParam(required = false) String subject, @AuthenticationPrincipal User currentUser) {
        List<QuestionResponse> questions = questionBankService.getPersonalizedPracticeQuestions(currentUser, subject)
                .stream()
                .map(QuestionResponse::fromEntity)
                .collect(Collectors.toList());
        return ResponseEntity.ok(questions);
    }

    @PostMapping("/questions/{questionId}/submit")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<AnswerFeedbackResponse> submitAnswer(@PathVariable Long questionId, @RequestBody SubmitAnswerRequest request, @AuthenticationPrincipal User currentUser) {
        AnswerFeedbackResponse feedback = practiceService.checkAnswer(questionId, request, currentUser);
        return ResponseEntity.ok(feedback);
    }
}
